package com.yupi.springbootinit.RabbitMQ;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class MqConsumer {

    private final static String WORK_EXCHANGE_NAME = "work";
    private final static String DEAD_EXCHANGE_NAME = "dead";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(WORK_EXCHANGE_NAME, "direct");
        Map<String, Object> args = new HashMap<>();
        //声明哪个是死信交换机
        args.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME);
        //死信存放的队列ps：死信队列
        args.put("x-dead-letter-routing-key", "ADead");
        channel.queueDeclare("A", true, false, false, args);
        channel.queueBind("A",WORK_EXCHANGE_NAME,"A");

        Map<String, Object> args2 = new HashMap<>();
        //声明哪个是死信交换机
        args2.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME);
        //死信存放的队列ps：死信队列
        args2.put("x-dead-letter-routing-key", "BDead");
        channel.queueDeclare("B", true, false, false, args2);
        channel.queueBind("B",WORK_EXCHANGE_NAME,"B");

        DeliverCallback AdeliverCallback = (consumerTag, deliver) -> {
            String messag = new String(deliver.getBody(), StandardCharsets.UTF_8);
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            channel.basicNack(deliver.getEnvelope().getDeliveryTag(),false,false);
            System.out.println("[A拒绝了:]" + messag);
        };
        DeliverCallback BdeliverCallback = (consumerTag, deliver) -> {
            String messa = new String(deliver.getBody(), StandardCharsets.UTF_8);
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            channel.basicNack(deliver.getEnvelope().getDeliveryTag(),false,false);
            System.out.println("[B拒绝了:]" + messa);
        };

        channel.basicConsume("A", false, AdeliverCallback, consumerTag -> {
        });
        channel.basicConsume("B", false, BdeliverCallback, consumerTag -> {
        });
    }
}